package com.jml.netty.version5;

import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.FixedLengthFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

public class NettyClient {

	public static void main(String[] args) throws InterruptedException {
		System.out.println("客户端已经启动....");
		// 创建负责接收客户端连接
		NioEventLoopGroup pGroup = new NioEventLoopGroup();
		Bootstrap bootstrap = new Bootstrap();
		bootstrap.group(pGroup).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
			@Override
			protected void initChannel(SocketChannel sc) throws Exception {

				//分隔符为_mayi
				ByteBuf buf = Unpooled.copiedBuffer("_mayi".getBytes());
				sc.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, buf));

				sc.pipeline().addLast(new StringDecoder());
				sc.pipeline().addLast(new ClientHandler());
			}
		});
		ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 8080).sync();
		channelFuture.channel().writeAndFlush(Unpooled.wrappedBuffer("我是客户端的数据1_mayi".getBytes()));
		channelFuture.channel().writeAndFlush(Unpooled.wrappedBuffer("我是客户端的数据2_mayi".getBytes()));
		//Thread.sleep(1000);
		channelFuture.channel().writeAndFlush(Unpooled.wrappedBuffer("我是客户端的数据3_mayi".getBytes()));
		channelFuture.channel().writeAndFlush(Unpooled.wrappedBuffer("我是客户端的数据4_mayi".getBytes()));
		// 等待客户端端口号关闭
		channelFuture.channel().closeFuture().sync();
		pGroup.shutdownGracefully();

	}




}
